package com.seata.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seata.feign.OrderFeign;
import com.seata.feign.StorageFeign;
import com.seata.mapper.AccountMapper;
import com.seata.model.Account;
import com.seata.model.BuyDTO;
import com.seata.model.Order;
import com.seata.model.Storage;
import com.seata.service.BusinessService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @Author: TongRui乀
 * @Date: 2019-12-05 17:11
 * @description：
 */
@Service
public class BusinessServiceImpl extends ServiceImpl<AccountMapper, Account> implements BusinessService {

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private OrderFeign orderFeign;

    @Autowired
    private StorageFeign storageFeign;

    @GlobalTransactional
    @Override
    public Integer buy(BuyDTO buyDTO) {

        System.err.println("全局事务ID：" + RootContext.getXID());
        try {

            // 创建订单
            Order order = new Order();
            order.setOrderNo("1111111");
            order.setUserId(buyDTO.getUserId());
            order.setCommodityCode(buyDTO.getCommodityCode());
            order.setCount(buyDTO.getCount());
            order.setAmount(buyDTO.getAmount());

            this.orderFeign.createOrder(order);

            // 扣库存
            Storage s = this.storageFeign.getStorageById(1);

            Storage storage = new Storage();
            storage.setId(1);
            storage.setCount(s.getCount() - 1);

            this.storageFeign.decreaseStorage(storage);
            // 扣余额

        }catch (Exception e){
            e.printStackTrace();
        }

        if(buyDTO.getCount() % 2 != 0){
            int a = 1 / 0;
        }

        return null;
    }
}